<?php


namespace App\Http\Controllers\Api\v1;

use App\common;
use App\Http\Controllers\Controller;
use App\Logic\LoginLogic;
use App\server\SMS\CodeServer;
use Illuminate\Http\Request;

class LoginController extends Controller
{

    /**
     * 发送验证码
     * @param Request $request
     * @return array|false|string
     * kys
     */
    public function verification(Request $request)
    {
        try {
            $phone = $request->get('phone');
            $type=$request->get('type');
            $code = CodeServer::sendCode($phone,$type);
            return common::success(20000,$code,'验证码发送成功');
        }catch (\Exception $exception){
            return common::fail('20001','',$exception->getMessage());
        }
    }

    /**
     * 验证验证码
     * @param Request $request
     * @return array|false|string
     * kys
     */
    public function verificationCode(Request $request){
        try {
            $key = $request->post();
            $status = CodeServer::verifyCode($key);
            if ($status == true){
                return common::success(20000,'','验证成功');
            }

        }catch (\Exception $exception){
            return common::fail('20001','',$exception->getMessage());
        }
    }


    public function index(){
        return view('admin/login');
    }

    public function login(Request $request){
        $params = $request->except('_token');

        //验证信息
        $post = $request->validate([
            'username' => 'required',
            'password' => 'required',
        ],[
            'username.required'=>'用户名不能为空',
            'password.required'=>'密码不能为空',
        ]);

        //验证信息
        //验证用户名密码是否正确
        $bool=auth()->attempt($post);

        if($bool){
            //判断用户是否超级管理员
            $auth = auth()->user()->username;
            //判断用户是否超级管理登录
            if($auth == config('rbac.super')){
                session(['admin_auths'=>true]);
            }else{

                //获取用户角色
                $role = auth()->user()->role;
                //获取用户权限
                $node = $role->nodes->pluck('route_name','id')->toArray();

                //缓存用户权限到session
                session(['admin_auths'=>$node]);
            }

            //登录成功跳转首页
            return redirect(route('admin/show'));
        }

        //登录失败返回
        return redirect(route('login'))->withErrors('用户名或密码错误');

    }


}
